﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ControlsLib;
using GestionePolveriLib.BL;
using BrightIdeasSoftware;
using GestionePolveriLib.Facades;
using GestionePolveri2.Filters;
using FrameworkLib.Filters;
using GestionePolveri2.DAL;
using GestionePolveriLib.BL.FilterBags;
using FrameworkLib.Utilities.Export;
using FrameworkLib.Configurations.FormsConfiguration;
using FrameworkLib.Configurations.FormsConfiguration.BL;
using FrameworkLib.Utilities;

namespace GestionePolveri2
{
    public partial class VerniciatoreScortaMinima : VerniciatoreScortaMinimaBase
    {
        List<ScortaMinimaInfo> m_polveriModificate = null;
        ScortaMinimaFacade pf = null;
        string[] columnsToHide = null;
        private bool m_dataChanged = false;

        public VerniciatoreScortaMinima()
        {
            InitializeComponent();
        }

        public override void InitializeForm()
        {
            System.Security.Principal.IPrincipal m_operatore = System.Threading.Thread.CurrentPrincipal;
            string[] roles = System.Web.Security.Roles.GetRolesForUser(m_operatore.Identity.Name);

            SavingConfigurationBag scb = new SavingConfigurationBag();
            scb.FormName = this.Name;
            scb.RoleName = roles[0];
            this.SavingConfigurationBag = scb;

            base.InitializeForm();

            this.CanModify = false;
            this.ShowOnlyCustomButton = true;

            this.AddCustomButton("btnSalva", "Salva");
            this.AddCustomButton("btnAllineamento", "Situazione Lotti");
            this.AddCustomButton("btnStampa", "Stampa");
            this.AddCustomButton("btnPrenotazione", "Prenota Polvere");
            this.AddCustomButton("btnAnnullaPrenotazione", "Annulla Prenotazione");
            this.AddCustomButton("btnModScortaMinima", "In riordino");
            this.AddCustomButton("btnCancelScortaMinima", "Annulla riordino");
            //this.AddCustomButton("btnExport", "Esporta in Excel");

            this.GetCustomButton("btnModScortaMinima").BackColor = Color.Yellow;
            this.GetCustomButton("btnCancelScortaMinima").BackColor = Color.Yellow;

            this.ButtonClicked += new EventHandler<CustomEventArgs<Polvere>>(Anagrafica_ButtonClicked);
            this.CustomButtonClicked += new EventHandler<CustomEventArgs<Polvere>>(Amministrazione2_CustomButtonClicked);

            this.ItemSelected += new EventHandler<CustomEventArgs<Polvere>>(Anagrafica_ItemSelected);

            this.objectListView1.ItemChecked += new ItemCheckedEventHandler(objectListView1_ItemChecked);
            this.objectListView1.CellEditStarting += new CellEditEventHandler(objectListView1_CellEditStarting);
            this.objectListView1.CellEditFinishing += new CellEditEventHandler(objectListView1_CellEditFinishing);
            //this.objectListView1.FormatRow += new EventHandler<FormatRowEventArgs>(objectListView1_FormatRow);
            this.objectListView1.CellClick += new EventHandler<CellClickEventArgs>(objectListView1_CellClick);
            this.objectListView1.FormatCell += new EventHandler<FormatCellEventArgs>(objectListView1_FormatCell);
            this.objectListView1.KeyDown += new KeyEventHandler(objectListView1_KeyDown);
            this.objectListView1.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(objectListView1_ItemSelectionChanged);

            this.contextMenuStrip1.ItemClicked += new ToolStripItemClickedEventHandler(contextMenuStrip1_ItemClicked);
            this.contextMenuStatoScortaMinima.ItemClicked += new ToolStripItemClickedEventHandler(contextMenuStatoScortaMinima_ItemClicked);
            //
            this.ShowCNFGMenu = true;

            this.InitializeButtonBar();

            this.objectListView1.UseCellFormatEvents = true;
            this.objectListView1.AlternateRowBackColor = System.Drawing.Color.Lavender;
            this.objectListView1.UseAlternatingBackColors = true;

            // forziamo la form ad aprirsi con un filtro impostato...
            this.IsFiltering = true;
            this.Filter.FilterBag.TipoLotto = LottoTypes.NonNulli;

            this.EnableButton("btnSalva", false);
            this.EnableButton("btnAnnulla", false);
        }

        void contextMenuStatoScortaMinima_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
        }

        void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == standardReportToolStripMenuItem.Name)
            {
                List<ScortaMinimaInfo> result = (List<ScortaMinimaInfo>)this.objectListView1.Objects;

                GestionePolveri2.Reports.ReportViewerDialog2 rpd2 = new GestionePolveri2.Reports.ReportViewerDialog2();
                rpd2.Datasource = result;
                rpd2.Report = "ReportSituazioneMagazzinoAVideo";
                rpd2.ReportViewer.PrinterSettings.DefaultPageSettings.Landscape = true;
                rpd2.ShowReport();
            }

            if (e.ClickedItem.Name == situazioneConLottiToolStripMenuItem.Name)
            {
                List<ScortaMinimaInfo> m_dati = new List<ScortaMinimaInfo>();

                m_dati = pf.GetScortaMinimaInfo2(this.Filter.FilterBag);

                GestionePolveri2.Reports.ReportViewerDialog2 rpd2 = new GestionePolveri2.Reports.ReportViewerDialog2();
                rpd2.Datasource = m_dati;
                rpd2.Report = "ReportSituazioneConLotti";
                rpd2.ReportViewer.PrinterSettings.DefaultPageSettings.Landscape = true;
                rpd2.ShowReport();
            }
        }

        void objectListView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
                if (c != null)  //OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
                {
                    AllineamentoInventarioDialog aid = new AllineamentoInventarioDialog();
                    aid.ScortaMinimaInfo = (ScortaMinimaInfo)c.RowObject;
                    if (aid.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        
                    }
                }
            }
        }

        void objectListView1_FormatCell(object sender, FormatCellEventArgs e)
        {
            Polvere m_polvere = (Polvere)e.Model;

            if (e.ColumnIndex == this.olvColumnScortaMinima.Index)
            {
                ScortaMinimaInfo m_scortaMinima = (ScortaMinimaInfo)e.Model;

                if (!m_scortaMinima.IsGeneratedByCorrection)
                {
                    if (m_polvere.QuantitaDisponibile < m_polvere.ScortaMinima)
                    {
                        e.SubItem.BackColor = Color.Red;

                        if (m_scortaMinima.DataRiordino.HasValue && !m_scortaMinima.DataChiusuraRiordino.HasValue)
                        {
                            e.SubItem.BackColor = Color.Yellow;
                        }
                    }
                    else
                    {
                        e.Item.SubItems[this.olvColumnScortaMinima.Index].BackColor = e.Item.SubItems[(this.olvColumnScortaMinima.Index == 0 ? 0 : this.olvColumnScortaMinima.Index - 1)].BackColor;
                    }
                }
                else
                {
                    if (((ScortaMinimaInfo)e.Model).DataChiusuraRiordino.HasValue)
                    {
                        e.SubItem.BackColor = Color.Orange;
                    }
                }
            }

            if ((m_polvere.QuantitaImpegnata > 0) && (m_polvere.QuantitaDisponibile < 0))
            {
                if (e.ColumnIndex == this.olvColumnQuantitaDisponibile.Index)
                {
                    e.SubItem.Decoration = new ImageDecoration(GestionePolveri2.Properties.Resources.warning_16x16, 255, ContentAlignment.MiddleLeft);
                }
            }

            if((m_polvere.QuantitaNC > 0) || (m_polvere.QuantitaNCBlocked > 0))
            {
                if (e.ColumnIndex == this.olvColumnCodicePolvere.Index)
                {
                    if ((m_polvere.QuantitaNC > 0) && (m_polvere.QuantitaNCBlocked > 0))
                    {
                        ImageDecoration imgdec = new ImageDecoration(GestionePolveri2.Properties.Resources.lgNC_AB, 255, ContentAlignment.MiddleRight);
                        e.SubItem.Decoration = imgdec; 
                    }
                    else
                    {
                        if (m_polvere.QuantitaNC > 0)
                        {
                            ImageDecoration imgdec = new ImageDecoration(GestionePolveri2.Properties.Resources.lgNC, 255, ContentAlignment.MiddleRight);
                            e.SubItem.Decoration = imgdec;
                        }
                        else
                        {
                            if (m_polvere.QuantitaNCBlocked > 0)
                            {
                                ImageDecoration imgdec = new ImageDecoration(GestionePolveri2.Properties.Resources.lgNC_B, 255, ContentAlignment.MiddleRight);
                                e.SubItem.Decoration = imgdec;
                            }
                        }
                    }
                }
            }
        }

        void objectListView1_CellClick(object sender, CellClickEventArgs e)
        {
        }

        protected override void OnLoadCompleted()
        {
            base.OnLoadCompleted();

            pf = new ScortaMinimaFacade();

            NascondiColonne();

            InizializzaCampi();
        }

        void Anagrafica_ButtonClicked(object sender, CustomEventArgs<Polvere> e)
        {
            switch (e.Action)
            {
                case Actions.New:
                    {
                    }
                    break;
                case Actions.Add:
                    {
                    }
                    break;
                case Actions.Modify:
                    {
                    }
                    break;
                case Actions.Delete:
                    {
                    }
                    break;
                default:
                    break;
            }
        }

        void Anagrafica_ItemSelected(object sender, CustomEventArgs<Polvere> e)
        {
            base.Current = e.Item;
        }

        void objectListView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            Polvere m_polvere = ((Polvere)((OLVListItem)e.Item).RowObject);

            if (this.Principal.IsInRole("Acquisti") || Principal.IsInRole("Amministrazione"))
            {
                OrdersDatesFacade odf = new OrdersDatesFacade();
                if (odf.CheckOpenOrder(m_polvere.ID))
                {
                    this.EnableButton("btnModScortaMinima", false);
                    this.EnableButton("btnCancelScortaMinima", true);
                }
                else
                {
                    if (m_polvere.Giacenza > m_polvere.ScortaMinima)
                    {
                        this.EnableButton("btnModScortaMinima", false);
                        this.EnableButton("btnCancelScortaMinima", false);
                    }
                    else
                    {
                        this.EnableButton("btnModScortaMinima", true);
                        this.EnableButton("btnCancelScortaMinima", false);
                    }
                }
            }
            else
            {
                this.EnableButton("btnModScortaMinima", false);
                this.EnableButton("btnCancelScortaMinima", false);
            }
        }

        void objectListView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            Polvere m_polvere = ((Polvere)((OLVListItem)e.Item).RowObject);
        }

        void objectListView1_CellEditStarting(object sender, CellEditEventArgs e)
        {
        }

        void objectListView1_CellEditFinishing(object sender, CellEditEventArgs e)
        {
            try
            {
                if (e.Cancel)
                {
                    base.OnShowNotificationMessage("Modifica annullata !");
                    return;
                }

                DateTime data;
                ScortaMinimaInfo polvere = (ScortaMinimaInfo)e.RowObject;

                if (e.Column.AspectName.Equals("ScortaMinima"))
                {
                    polvere.ScortaMinima = double.Parse(e.NewValue.ToString());
                    ScortaMinimaFacade sf = new ScortaMinimaFacade();
                    sf.ModifyScortaMinimaInfo(polvere);
                }

                if (e.Column.AspectName.Equals("Note"))
                {
                    polvere.Note = e.NewValue.ToString();
                    ScortaMinimaFacade sf = new ScortaMinimaFacade();
                    sf.ModifyScortaMinimaInfo(polvere);
                }

                if (e.Column.AspectName.Equals("DataControllo"))
                {
                    if ((e.Value != null) && (e.Value.Equals(e.NewValue)))
                    {
                        return;
                    }

                    if (!string.IsNullOrEmpty(e.NewValue.ToString()))
                    {
                        if (!DateTime.TryParse(e.NewValue.ToString(), out data))
                        {
                            MessageBox.Show("digitare la data nel formato gg/mm/aaaa");
                        }
                        else
                        {
                            DateTime dt = DateTime.Parse(e.NewValue.ToString());
                            ((ScortaMinimaInfo)e.RowObject).DataControllo = dt;
                            m_dataChanged = true;

                            // Aggiorno subito i lotti associati alla polvere e salvo...
                            ScortaMinimaFacade sf = new ScortaMinimaFacade();
                            LottoFacade lf = new LottoFacade();

                            sf.Transact(() =>
                            {
                                sf.ModifyScortaMinimaInfo(polvere);

                                lf.AggDtCtrPolvere(polvere.ID, dt);

                            }, sf.GetContext());
                        }
                    }
                }

                base.OnShowNotificationMessage("Dati salvati correttamente !");
                //MessageBox.Show("Dati salvati correttamente !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Errore durante il salvataggio dei dati: " + ex.Message, "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void objectListView1_FormatRow(object sender, FormatRowEventArgs e)
        {
            //Polvere polvere = (Polvere)e.Model;
            //if (polvere.QuantitaDisponibile < polvere.ScortaMinima)
            //{
            //    this.objectListView1.Items[e.RowIndex].BackColor = Color.Red;
            //}
        }

        void Amministrazione2_CustomButtonClicked(object sender, CustomEventArgs<Polvere> e)
        {
            #region Modifica scorta minima
            if (e.ButtonName.Equals("btnCancelScortaMinima", StringComparison.InvariantCultureIgnoreCase))
            {
                OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
                if (c == null)
                {
                    MessageBox.Show("Selezionare una polvere!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (this.olvColumnScortaMinima.Index >= 0)
                    {
                        c.SubItems[this.olvColumnScortaMinima.Index].BackColor = c.SubItems[(this.olvColumnScortaMinima.Index == 0 ? 0 : this.olvColumnScortaMinima.Index - 1)].BackColor;
                    }

                    OrdersDatesFacade odf = new OrdersDatesFacade();
                    odf.CancelOrderDate(((ScortaMinimaInfo)c.RowObject).ID);

                    ((ScortaMinimaInfo)c.RowObject).DataRiordino = null;
                    ((ScortaMinimaInfo)c.RowObject).DataChiusuraRiordino = null;

                    MessageBox.Show("Riordino Scorta Minima annullato!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            if (e.ButtonName.Equals("btnModScortaMinima", StringComparison.InvariantCultureIgnoreCase))
            {
                OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
                if (c == null)
                {
                    MessageBox.Show("Selezionare una polvere!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    if (this.olvColumnScortaMinima.Index >= 0)
                    {
                        c.SubItems[this.olvColumnScortaMinima.Index].BackColor = Color.Yellow;
                    }

                    OrdersDatesFacade odf = new OrdersDatesFacade();
                    if (odf.SetOrderDate(((ScortaMinimaInfo)c.RowObject).ID))
                    {
                        ((ScortaMinimaInfo)c.RowObject).DataRiordino = DateTime.Now;
                        ((ScortaMinimaInfo)c.RowObject).DataChiusuraRiordino = null;

                        MessageBox.Show("Riordino Scorta Minima impostata!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Riordino Scorta Minima già effettuato !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            #endregion

            #region btnAllineamento
            if (e.ButtonName.Equals("btnAllineamento", StringComparison.InvariantCultureIgnoreCase))
            {
                if (e.Item != null)  //OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
                {
                    AllineamentoInventarioDialog aid = new AllineamentoInventarioDialog();
                    aid.ScortaMinimaInfo = (ScortaMinimaInfo)e.Item;
                    
                    if (aid.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;

                        if (aid.DataControllo != DateTime.MinValue)
                        {
                            ((ScortaMinimaInfo)e.Item).DataControllo = aid.DataControllo;
                            if(c != null) this.objectListView1.RefreshItem(c);
                        }

                        LoadData(this.Filter.FilterBag);

                        int index = 0;
                        foreach (ScortaMinimaInfo smi in (List<ScortaMinimaInfo>)this.objectListView1.Objects)
                        {
                            if (smi.CodicePolvere == ((ScortaMinimaInfo)e.Item).CodicePolvere)
                            {
                                this.objectListView1.SelectedIndex = index;
                                break;
                            }

                            index++;
                        }
                    }
                }
                else
                    MessageBox.Show("Selezionare una polvere!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            #endregion

            #region btnExport
            if (e.ButtonName.Equals("btnExport", StringComparison.InvariantCultureIgnoreCase))
            {
                ScortaMinimaFacade pf = new ScortaMinimaFacade();
                pf.RunAsync(() => GetDataToExport(), (result) =>  //   () => pf.GetMovimenti(), (result) =>
                {
                    if (result != null)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Filter = "Excel Files (.xls)|*.xls|All Files (*.*)|*.*";
                        sfd.FilterIndex = 1;
                        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            string errorMessage = string.Empty;
                            if (((List<ScortaMinimaInfo>)result).ToExcel(sfd.FileName, out errorMessage, columnsToHide))
                            {
                                MessageBox.Show("Esportazione in Excel effettuata!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                MessageBox.Show(string.Format("ATTENZIONE: Si è verificato un errore: {0}", errorMessage), "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Nessun dato da inviare in stampa.", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                });
            }
            #endregion

            #region btnStampa
            if (e.ButtonName.Equals("btnStampa", StringComparison.InvariantCultureIgnoreCase))
            {
                Button btn = this.ButtonBar.GetCustomButton("btnStampa");
                this.contextMenuStrip1.Show(btn, new Point(0, 0), ToolStripDropDownDirection.AboveRight);


                // stampa usando la funzione della ObjectListView...
                //BrightIdeasSoftware.ListViewPrinter lvp = new ListViewPrinter();
                //lvp.ListView = this.objectListView1;
                //lvp.Header = this.Text;
                //lvp.HeaderFormat.Font = new Font(FontFamily.GenericSerif, 10);
                //lvp.IsShrinkToFit = false;
                //lvp.DefaultPageSettings.Landscape = true;
                //lvp.PrintPreview();

                //LottoFacade pf = new LottoFacade();
                //pf.RunAsync(() => pf.GetLottiByPolvereList(), (result) => 
                //{
                //    if (result != null)
                //    {
                //        GestionePolveri2.Reports.ReportViewerDialog2 rpd2 = new GestionePolveri2.Reports.ReportViewerDialog2();
                //        //rpd2.Datasource = this.dataGridView1.DataSource;
                //        rpd2.Datasource = result;
                //        rpd2.Report = "ReportSituazioneMagazzino";
                //        rpd2.ReportViewer.PrinterSettings.DefaultPageSettings.Landscape = true;
                //        rpd2.ShowReport();
                //    }
                //});
            }
            #endregion

            #region btnSalva
            if (e.ButtonName.Equals("btnSalva", StringComparison.InvariantCultureIgnoreCase))
            {
            }

            if (e.ButtonName.Equals("btnSalva___", StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    if (m_polveriModificate.Count() > 0)
                    {
                        if (m_dataChanged)
                        {

                            if (MessageBox.Show("Stai per Aggiornare la data controllo su tutti i lotti della polvere.\n\rVuoi Proseguire ?", "Gestione Polveri",
                                                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                            {
                                return;
                            }
                        }

                        //e.Action = Actions.Unselected;
                        ScortaMinimaFacade sf = new ScortaMinimaFacade();
                        LottoFacade lf = new LottoFacade();

                        pf.Transact(() =>
                        {
                            foreach (ScortaMinimaInfo p in m_polveriModificate)
                            {
                                sf.ModifyScortaMinimaInfo(p);

                                if (p.DataControllo.HasValue)
                                {
                                    lf.AggDtCtrPolvere(p.ID, p.DataControllo.Value);
                                }
                            }
                        });

                        m_dataChanged = false;
                        MessageBox.Show("Dati salvati correttamente !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Errore durante il salvataggio dei dati: " + ex.Message, "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                base.ClearControls(this.Controls);

                ManageData();
                //LoadData(false);
            }
            #endregion

            #region Prenotazione
            if (e.ButtonName.Equals("btnPrenotazione", StringComparison.InvariantCultureIgnoreCase))
            {
                OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;

                if (c == null)
                {
                    MessageBox.Show("Selezionare una riga.", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                PrenotazioneManager pm = new PrenotazioneManager();
                pm.Polvere = (Polvere)c.RowObject;
                if (pm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    MessageBox.Show(string.Format("Prenotazione Effettuata di {0:N} Kg. per la polvere {1} !",  pm.Polvere.QuantitaImpegnata, pm.Polvere.CodicePolvere), 
                        "Gestione Polveri",MessageBoxButtons.OK, MessageBoxIcon.Information);

                    ManageData();
                }
            }

            if (e.ButtonName.Equals("btnAnnullaPrenotazione", StringComparison.InvariantCultureIgnoreCase))
            {
                ElencoPrenotazioni ep = new ElencoPrenotazioni();
                ep.StartPosition = FormStartPosition.CenterScreen;
                ep.MinimizeBox = false;
                ep.MaximizeBox = false;
                ep.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
                ep.Load += (s, ev) => ep.InitializeForm();
                
                if (ep.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ManageData();
                }
            }
            #endregion
        }

        private void NascondiColonne()
        {
            OperatorePrincipal m_OperatorePrincipale = (OperatorePrincipal)System.Threading.Thread.CurrentPrincipal;
            if (m_OperatorePrincipale.IsInRole("Amministrazione"))
            {
                this.olvColumnDataControllo.IsEditable = true;
                this.olvColumnScortaMinima.IsEditable = true;
                this.olvColumnNote.IsEditable = true;
            }

            if (m_OperatorePrincipale.IsInRole("Verniciatura"))
            {
                this.olvColumnDataControllo.IsEditable = true;
                this.olvColumnScortaMinima.IsEditable = false;

                this.objectListView1.AllColumns.Remove(this.olvColumnCaricoScaricoDiff);
                this.objectListView1.AllColumns.Remove(this.olvColumnPrezzo);
                this.objectListView1.AllColumns.Remove(this.olvColumnValore);

                this.lblTotValore.Visible = false;

                this.objectListView1.RebuildColumns();

                columnsToHide = new string[] {
                                 this.olvColumnPrezzo.AspectName,
                                 this.olvColumnValore.AspectName,
                };
            }

            if (m_OperatorePrincipale.IsInRole("Produzione"))
            {
                this.olvColumnDataControllo.IsEditable = false;

                this.objectListView1.AllColumns.Remove(this.olvColumnCaricoScaricoDiff);
                this.objectListView1.AllColumns.Remove(this.olvColumnPrezzo);
                this.objectListView1.AllColumns.Remove(this.olvColumnValore);

                this.lblTotValore.Visible = false;

                this.objectListView1.RebuildColumns();

                columnsToHide = new string[] {
                                 this.olvColumnPrezzo.AspectName,
                                 this.olvColumnValore.AspectName,
                };

                this.EnableButton("btnCancel", false);
            }

            if (m_OperatorePrincipale.IsInRole("Direzione"))
            {
                this.objectListView1.AllColumns.Remove(this.olvColumnCaricoScaricoDiff);

                this.olvColumnDataControllo.IsEditable = false;
                this.olvColumnScortaMinima.IsEditable = false;
                this.olvColumnNote.IsEditable = false;

                this.EnableButton("btnSalva", false);
                this.EnableButton("btnCancel", false);
            }

            if (m_OperatorePrincipale.IsInRole("Acquisti"))
            {
                this.objectListView1.AllColumns.Remove(this.olvColumnCaricoScaricoDiff);

                this.olvColumnDataControllo.IsEditable = false;
                this.olvColumnScortaMinima.IsEditable = true;
                this.olvColumnNote.IsEditable = false;

                this.EnableButton("btnCancel", false);
            }

            this.objectListView1.RebuildColumns();

        }

        private List<ScortaMinimaInfo> GetDataToExport()
        {
            List<ScortaMinimaInfo> retValue = null;

            ScortaMinimaFacade pf = new ScortaMinimaFacade();

            retValue = (this.IsFiltering ? pf.GetScortaMinimaInfo(this.Filter.FilterBag) : pf.GetScortaMinimaInfo());

            return retValue;
        }

        private void InizializzaCampi()
        {
            m_polveriModificate = new List<ScortaMinimaInfo>();

            this.ShowFilterTracing = true;

            this.EnableButton("btnModScortaMinima", false);

            System.Security.Principal.IPrincipal m_operatore = System.Threading.Thread.CurrentPrincipal;
            if (m_operatore.IsInRole("Direzione") || m_operatore.IsInRole("Produzione"))
            {
                this.olvColumnScortaMinima.IsEditable = false;
                this.EnableButton("btnSalva", false);               
            }

            if (m_operatore.IsInRole("Acquisti") || m_operatore.IsInRole("Amministrazione"))
            {
                this.EnableButton("btnModScortaMinima", true);
            }

            ManageData();
        }

        public override void OnRefreshFilterData()
        {
            base.OnRefreshFilterData();

            this.objectListView1.Unsort();

            ManageData();
        }

        public override void OnFilterReset()
        {
            base.OnFilterReset();

            this.IsFiltering = false;

            this.objectListView1.Unsort();

            ManageData();
        }

        public override void OnFilterExecuted()
        {
            base.OnFilterExecuted();

            this.IsFiltering = true;

            this.objectListView1.Unsort();

            ManageData();
        }

        private void ManageData()
        {
            SuspendLayout1();

            LoadData(this.Filter.FilterBag);

            ResumeLayout1();
        }

        private void ResumeLayout1()
        {
            this.groupBox1.ResumeLayout(false);
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).EndInit();
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
            this.splitContainer1.ResumeLayout(false);
            this.ResumeLayout(false);
        }

        private void SuspendLayout1()
        {
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            this.SuspendLayout();
        }

        private void LoadData(bool selectLast)
        {
            pf.RunAsync<List<ScortaMinimaInfo>>(() => pf.GetScortaMinimaInfo(), (result) =>
            {
                if (result != null)
                {
                    this.objectListView1.AddDecoration(new EditingCellBorderDecoration { UseLightbox = true });
                    this.objectListView1.SetObjects((List<ScortaMinimaInfo>)result, true);

                    CalcolaTotali((List<ScortaMinimaInfo>)result);
                }
                else
                {
                    this.objectListView1.Items.Clear();
                    this.objectListView1.EmptyListMsg = "Nessun Dato Trovato !";
                }
            });
        }

        private void LoadData(FilterBase<AnagPolveri> filter)
        {
            pf.RunAsync<List<ScortaMinimaInfo>>(() => pf.GetScortaMinimaInfo(filter), (result) =>
            {
                if (this.IsDisposed) return;

                if (result != null)
                {
                    if (this.Filter.FilterBag.TipoLotto == LottoTypes.Tutti)
                    {
                        this.objectListView1.Sort(this.olvColumnGiacenza, SortOrder.Descending);
                    }

                    this.objectListView1.AddDecoration(new EditingCellBorderDecoration { UseLightbox = true });
                    this.objectListView1.SetObjects((List<ScortaMinimaInfo>)result);

                    CalcolaTotali((List<ScortaMinimaInfo>)result);
                }
                else
                {
                    this.objectListView1.Items.Clear();
                    this.objectListView1.EmptyListMsg = "Nessun Dato Trovato !";

                    this.ResetButtons();
                    this.ClearControls(this.Controls);

                    this.objectListView1.Items.Clear();
                }
            });
        }

        private void CalcolaTotali(List<ScortaMinimaInfo> result)
        {
            double m_totaleGiacenza = 0;
            double m_totaleValore = 0;
            double m_totaleCarico = 0;
            double m_totaleScarico = 0;

            foreach (ScortaMinimaInfo sci in result)
            {
                m_totaleGiacenza += sci.Giacenza.GetValueOrDefault();
                m_totaleValore += sci.Valore;
                m_totaleCarico += sci.Carico;
                m_totaleScarico += sci.Scarico;
            }

            this.lblTotCarico.Text = string.Format("TOT Carico: {0:N}", m_totaleCarico);
            this.lblTotScarico.Text = string.Format("TOT Scarico: {0:N}", m_totaleScarico);

            this.lblTotGiacenza.Text = string.Format("Totale Giacenza: {0:N}", m_totaleGiacenza);
            this.lblTotValore.Text = string.Format("Totale Valore: {0:C}", m_totaleValore);
        }

        private void RefreshColumns()
        {
            ColumnsConfigurationManager ccm = new ColumnsConfigurationManager();
            byte[] state = ccm.GetState(this.Name);

            if (state != null)
            {
                bool result = this.objectListView1.RestoreState(state);
            }

            NascondiColonne();
        }
    }

    public class VerniciatoreScortaMinimaBase : AnagraficaManagerFilteredObjectListView<Polvere, VerniciatoreScortaMinimaFilter, VerniciatoreScortaMinimaFilterBag> { }
}
